﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using LinqToEdmx;
using Magiq.Support;

namespace Magiq.Providers.Entities
{
    public static class EdmxProvder
    {
        private static readonly IDictionary<string,Edmx> Index = new Dictionary<string, Edmx>();
 
        public static Edmx From(Type type, ObjectContext context)
        {
            var connectionString = context.Connection.ConnectionString.ToLower();
            Edmx edmx;

            if (!Index.TryGetValue(connectionString, out edmx))
            {
                var mapping = context.Connection.ConnectionString.ToLower()
                    .GetFrom("metadata=")
                    .GetUntil(";")
                    .Replace("res://*", "res://" + type.Assembly.FullName);

                edmx = Edmx.Load(mapping);
                Index.Add(connectionString, edmx);
            }

            return edmx;
        }
    }
}